package com.kedacom.demo.quartz2;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.stereotype.Component;

/**
 * This JobFactory autowires automatically the created quartz bean with spring @Autowired
 * dependencies. Autowire Quartz Jobs with Spring context dependencies
 * @see http
 *      ://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-
 *      quartz -job-in-spring/15211030#15211030
 */
@Component("autowiringSpringBeanJobFactory")
public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

	private transient AutowireCapableBeanFactory beanFactory;

	@Override
	public void setApplicationContext(final ApplicationContext context) {
		beanFactory = context.getAutowireCapableBeanFactory();
	}

	@Override
	protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
		final Object job = super.createJobInstance(bundle);
		beanFactory.autowireBean(job);
		return job;
	}

}
